<?php
header('Content-Type: application/json');

require_once __DIR__.'/vendor/autoload.php';
use PhpOffice\PhpSpreadsheet\IOFactory;

$config = require __DIR__.'/config.php';

// 检查是否有文件上传
$files = [];
foreach ($_FILES as $key => $file) {
    if (strpos($key, 'file') === 0 && $file['error'] === UPLOAD_ERR_OK) {
        $files[] = $file;
    }
}

// 提取Excel文件内容
$excelContents = [];
foreach ($files as $file) {
    try {
        $spreadsheet = IOFactory::load($file['tmp_name']);
        $worksheet = $spreadsheet->getActiveSheet();
        $data = $worksheet->toArray();
        
        // 移除空行
        $data = array_filter($data, function($row) {
            return !empty(array_filter($row));
        });
        
        // 提取表头
        $headers = array_shift($data);
        
        // 结构化数据
        $structuredData = [];
        foreach ($data as $row) {
            $rowData = [];
            foreach ($headers as $index => $header) {
                $rowData[$header] = $row[$index] ?? '';
            }
            $structuredData[] = $rowData;
        }
        
        $excelContents[] = [
            'filename' => $file['name'],
            'sheet_name' => $worksheet->getTitle(),
            'headers' => $headers,
            'data' => $structuredData
        ];
    } catch (Exception $e) {
        error_log("Excel处理错误: " . $e->getMessage());
        $excelContents[] = [
            'filename' => $file['name'],
            'error' => "文件处理失败: " . $e->getMessage()
        ];
    }
}

// 构建系统提示信息
$systemPrompt = "你是一个数据分析助手。我会给你一些Excel文件的内容，你需要根据这些数据回答用户的问题。\n\n";
foreach ($excelContents as $content) {
    if (isset($content['error'])) {
        $systemPrompt .= "文件 {$content['filename']} 处理失败：{$content['error']}\n\n";
        continue;
    }
    
    $systemPrompt .= "文件 {$content['filename']} 的工作表 {$content['sheet_name']} 的内容：\n";
    $systemPrompt .= "表头：" . implode(", ", $content['headers']) . "\n";
    $systemPrompt .= "数据示例（前3行）：\n";
    
    $rowCount = 0;
    foreach ($content['data'] as $row) {
        if ($rowCount >= 3) break;
        $systemPrompt .= implode(", ", array_values($row)) . "\n";
        $rowCount++;
    }
    
    $systemPrompt .= "总行数：" . count($content['data']) . "\n\n";
}

if (!isset($_POST['model']) || !isset($config[$_POST['model']])) {
    http_response_code(500);
    echo json_encode(['error' => '不支持的模型类型'.$_POST['model']]);
    exit;
}

$model_config = $config[$_POST['model']];

// 检查API密钥
if (empty($model_config['api_key'])) {
    $keyApplyLinks = [
        'ernie' => 'https://cloud.baidu.com/doc/WENXINWORKSHOP/index.html',
        'deepseek' => 'https://platform.deepseek.com/',
        'qwen' => 'https://dashscope.aliyuncs.com/'
    ];
    $modelNames = [
        'ernie' => '文心一言',
        'deepseek' => '深度求索',
        'qwen' => '通义千问'
    ];
    $link = $keyApplyLinks[$_POST['model']] ?? '';
    $modelName = $modelNames[$_POST['model']] ?? $_POST['model'];
    
    error_log("API密钥未配置 - 模型: {$_POST['model']}, 链接: {$link}");
    
    http_response_code(500);
    echo json_encode([
        'error' => "{$modelName} API密钥未配置，请先申请API密钥。",
        'link' => $link
    ], JSON_UNESCAPED_UNICODE);
    exit;
}

try {
    if (!isset($_POST['message'])) {
        throw new Exception('缺少消息内容');
    }

    $ch = curl_init($model_config['endpoint']);
    
    // 根据模型类型处理消息
    $messages = [];
    if ($_POST['model'] === 'ernie') {
        $messages = [
            ['role' => 'system', 'content' => $systemPrompt],
            ['role' => 'user', 'content' => $_POST['message']]
        ];
    } else {
        $messages = [
            ['role' => 'system', 'content' => $systemPrompt],
            ['role' => 'user', 'content' => $_POST['message']]
        ];
    }

    curl_setopt_array($ch, [
        CURLOPT_HTTPHEADER => array_merge(
            ['Content-Type: application/json'],
            $_POST['model'] === 'ernie' ? [
                'Authorization: Bearer ' . $model_config['api_key'],
                'Accept: application/json'
            ] : ['Authorization: Bearer ' . $model_config['api_key']]
        ),
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => json_encode(
            array_merge(
                (function() use ($messages) {
                    $model = $_POST['model'];
                    switch($model) {
                        case 'ernie':
                            return [
                                'messages' => array_map(function($msg) {
                                    return [
                                        'role' => $msg['role'],
                                        'content' => $msg['content']
                                    ];
                                }, $messages),
                                'temperature' => 0.7,
                                'model' => 'ernie-bot-4',
                                'stream' => false
                            ];
                        case 'qwen':
                            return [
                                'model' => 'qwen-turbo',
                                'input' => ['messages' => $messages],
                                'parameters' => ['temperature' => 0.7]
                            ];
                        default:
                            return [
                                'model' => 'deepseek-chat',
                                'messages' => $messages,
                                'temperature' => 0.7
                            ];
                    }
                })(),
                ['stream' => false]
            )
        ),
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_SSL_VERIFYHOST => 0,
        CURLOPT_TIMEOUT => 30
    ]);

    $response = curl_exec($ch);
    
    $logResult = file_put_contents(__DIR__.'/api_debug.log', date('Y-m-d H:i:s')." Response: ".$response.PHP_EOL, FILE_APPEND);
    if ($logResult === false) {
        throw new Exception('日志写入失败，请检查目录权限');
    }

    if (curl_errno($ch)) {
        throw new Exception('API请求失败: ' . curl_error($ch));
    }

    $result = json_decode($response, true);
    if ($_POST['model'] === 'qwen' && isset($result['code'])) {
        throw new Exception('API错误: ' . $result['message']);
    } elseif ($_POST['model'] === 'ernie' && isset($result['error_code'])) {
        throw new Exception('API错误: ' . $result['error_msg']);
    } elseif (isset($result['error'])) {
        throw new Exception('API错误: ' . $result['error']['message']);
    }

    echo json_encode([
        'content' => (function() use ($result) {
            $rawContent = '';
            switch ($_POST['model']) {
                case 'ernie':
                    $rawContent = $result['result'] ?? $result['response'] ?? '';
                    break;
                case 'qwen':
                    $rawContent = $result['output']['text'];
                    break;
                default:
                    $rawContent = $result['choices'][0]['message']['content'];
            }

            // 生成HTML内容
            $htmlContent = preg_replace('/\\*\\*(.*?)\\*\\*/', '<strong>$1</strong>', $rawContent);
            $lines = array_filter(explode("\n", $htmlContent), function($line) {
                return trim($line) !== '';
            });
            
            $html = '<ul class="store-list">';
            foreach ($lines as $line) {
                if (preg_match('/^\d+\./', $line)) {
                    $html .= '<li class="store-item">'.substr($line, 2).'</li>';
                } else {
                    $html .= '<li class="store-info">'.$line.'</li>';
                }
            }
            $html .= '</ul>';

            return [
                'text' => $rawContent,
                'html' => $html
            ];
        })()
    ]);

} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['error' => $e->getMessage()]);
}